HackerRank Sherlock and MiniMax
提出
Terminated due to timeout :(
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'sherlockAndMinimax' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY arr
# 2. INTEGER p
# 3. INTEGER q
#
def sherlockAndMinimax(arr, p, q):
# Write your code here
res = []
for i in range(p, q+1):
i_ans = float('inf')
for j in arr:
if (abs(i - j) < i_ans):
i_ans = abs(i - j)
res.append(i_ans)
ans = max(res)
return res.index(ans) + p
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
first_multiple_input = input().rstrip().split()
p = int(first_multiple_input0) q = int(first_multiple_input1) result = sherlockAndMinimax(arr, p, q)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'sherlockAndMinimax' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY arr
# 2. INTEGER p
# 3. INTEGER q
#
def sherlockAndMinimax(arr, p, q):
# Write your code here
arr = sorted(arr)
new_arr = []
minx = -1
ans = -1
ans = p
ans = q
for i in range(0, len(arr)-1):
mid = (arri + arri+1) // 2 if mid <= q and mid >= p and (mid-arri) > minx: ans = mid
elif mid > q:
ans = q
elif mid < p:
ans = p
return ans
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
first_multiple_input = input().rstrip().split()
p = int(first_multiple_input0) q = int(first_multiple_input1) result = sherlockAndMinimax(arr, p, q)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=UOcfNW0sWkU
https://scrapbox.io/files/61d16da19363d3001debc648.png